/** 表单校验 */

import type { FormRules } from 'nutui-uniapp'
import type { Ref } from 'vue'

export const loginRules: FormRules = {
  phone: [
    { required: true, message: '请填写手机号' },
    {
      message: '手机号格式有误',
      validator: (val: string) => /^1[3-9]\d{9}$/.test(val),
    },
  ],
  code: [{ required: true, message: '请填写验证码' }],
  passport: [{ required: true, message: '请填写账号' }],
  password: [{ required: true, message: '请填写密码' }],
}

type formName = 'phone' | 'code' | 'passport' | 'password'

/**
 * 简化版规则验证，可以在非form中使用
 *
 * @param names 需要验证的字段
 * @param formData 表单数据
 * @returns {boolean} Returns true if all validation rules pass without errors.
 */
export function checkRules(names: formName[], formData: Ref): boolean {
  for (const name of names) {
    if (loginRules[name]) {
      for (const rule of loginRules[name]) {
        if (rule.required && !formData.value[name]) {
          throw new Error(rule.message)
        }
        else if (typeof rule.validator === 'function') {
          const result = rule.validator(formData.value[name], {
            message: rule.message,
          })
          if (!result) {
            throw new Error(rule.message)
          }
        }
      }
    }
  }
  return true
}
